/**
 * Copyright 2023 Inc.
 **/
package com.myz.design.interceptor;

import org.apache.commons.lang3.concurrent.ConcurrentException;
import org.apache.commons.lang3.concurrent.LazyInitializer;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.ServiceLoader;

/**
 * @author maoyz0621 on 2023/7/20
 * @version v1.0
 */
public class ConsumerInterceptorFactory {

    private static final LazyInitializer<ConsumerInterceptor> INTERCEPTORS = new LazyInitializer<ConsumerInterceptor>() {

        @Override
        protected ConsumerInterceptor initialize() throws ConcurrentException {
            ServiceLoader<ConsumerInterceptor> serviceLoader = ServiceLoader.load(ConsumerInterceptor.class);
            List<ConsumerInterceptor> consumerInterceptorList = new ArrayList<>();
            for (ConsumerInterceptor consumerInterceptor : serviceLoader) {
                consumerInterceptorList.add(consumerInterceptor);
            }

            consumerInterceptorList.sort(Comparator.comparing(ConsumerInterceptor::getOrder));
            return new ConsumerInterceptors(consumerInterceptorList);
        }
    };

    public static ConsumerInterceptor interceptors() {
        try {
            return (ConsumerInterceptor) INTERCEPTORS.get();
        } catch (ConcurrentException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    public static void main(String[] args) throws ConcurrentException {
        ConsumerInterceptorFactory.interceptors().consume();
    }
}